package com.piece.mall.service;

import com.piece.core.framework.enums.StatusType;
import com.piece.core.framework.enums.sql.SqlKey;
import com.piece.core.framework.support.bootstrap.Order;
import com.piece.core.jpa.repository.BaseService;
import com.piece.mall.model.PmsAttr;
import com.piece.mall.model.PmsProductAttrValue;
import com.piece.mall.repository.PmsAttrRepository;
import com.piece.mall.repository.PmsProductAttrValueRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Transactional
public class PmsProductAttrValueService extends BaseService<PmsProductAttrValue, String> {

    @Autowired
    private PmsProductAttrValueRepository pmsProductAttrValueRepository;

    @Resource
    private PmsAttrRepository pmsAttrRepository;

    @PostConstruct
    public void initRepository() {
        setRepository(pmsProductAttrValueRepository);
    }

    /**
     * 查询spu对应规格参数
     */
    public List<PmsProductAttrValue> findBySpuId(Long spuId) {
        return pmsProductAttrValueRepository.findByCondition("spuId", spuId, Arrays.asList(new Order("attrSort", SqlKey.ASC)));
    }

    /**
     * 保存spu基本参数属性
     */
    public void saveProductAttrValue(Long spuId, List<PmsAttr> baseAttrs) {
        List<Long> attrIds = baseAttrs.stream().map(baseAttr -> baseAttr.getAttrId()).collect(Collectors.toList());
        List<PmsAttr> attrs = pmsAttrRepository.findByCondition("Q_attrId_L_IN", attrIds, null);
        Map<Long, PmsAttr> attrMap = attrs.stream().collect(Collectors.toMap(key -> key.getAttrId(), val -> val));
        List<PmsProductAttrValue> attrValues = baseAttrs.stream().map(attr -> {
            if (StatusType.NORMAL.getCode().equals(attr.getShowDesc())) {
                PmsProductAttrValue attrValue = new PmsProductAttrValue();
                attrValue.setSpuId(spuId);
                attrValue.setAttrId(attr.getAttrId());
                attrValue.setAttrName(attrMap.get(attr.getAttrId()).getAttrName());
                attrValue.setAttrValue(attr.getAttrValue());
                attrValue.setQuickShow(attr.getShowDesc());
                return attrValue;
            }
           return null;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        pmsProductAttrValueRepository.batchInsert(attrValues);
    }

    /**
     * 删除spu基本参数属性
     */
    public void deleteProductAttrValue(Long spuId) {
        pmsProductAttrValueRepository.deleteByProperties("spuId", spuId);
    }
}
